package ru.dc.gui.swing;

import org.jdesktop.swingx.JXTable;
import ru.dc.Application;
import ru.dc.gui.UsersStore;
import ru.dc.gui.swing.util.IconLoader;
import ru.dc.gui.swing.util.SizeRenderer;

import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: deady
 * Date: 08.10.2010
 * Time: 22:29:09
 */
public class SingleHubWindow extends Tab {
    private JTextArea output;
    private JPanel rootPanel;
    private JXTable users;
    private JTextField message;
    private JButton sendMessageBtn;
    private JTextField topic;
    private JButton reconnectBtn;
    private JButton disconnectBtn;
    private java.util.List<SendMessageListener> sendMessageListeners = new ArrayList<SendMessageListener>();



    @Override
    public void init() {
        setIcon(IconLoader.getInstance().getIcon("network-hub.png"));
        setLayout(new BorderLayout());
        add(rootPanel);

        users.setModel(new UsersModel());
        users.getColumnModel().getColumn(1).setCellRenderer(new SizeRenderer());
        users.setSortOrder(0, SortOrder.ASCENDING);

        message.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "sendMessage");
        message.getActionMap().put("sendMessage", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                fireMessageSending(message.getText());
                message.setText("");
            }
        });

        sendMessageBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fireMessageSending(message.getText());
                message.setText("");
            }
        });
    }

    private void fireMessageSending(String text) {
        for (SendMessageListener listener : sendMessageListeners) {
            listener.onMessageSend(text);
        }
    }

    @Override
    public void onSelect() {
        super.onSelect();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                message.requestFocusInWindow();
            }
        });
    }

    public JTextArea getOutput() {
        return output;
    }

    public JXTable getUsers() {
        return users;
    }

    public void addSendMessageListener(SendMessageListener listener) {
        sendMessageListeners.add(listener);
    }

    public JTextField getTopic() {
        return topic;
    }

    public JTextField getMessage() {
        return message;
    }

    public JButton getSendMessageBtn() {
        return sendMessageBtn;
    }

    public JButton getReconnectBtn() {
        return reconnectBtn;
    }

    public JButton getDisconnectBtn() {
        return disconnectBtn;
    }
}
